package com.wushijia.highconcurrency;

import java.util.concurrent.locks.ReentrantLock;

/**
 * description:lockInterruptibly()：获得锁，但优先响应中断
 *
 * @author yang
 * @date 2018/5/16 21:30
 */
public class IntLock implements Runnable {

  private static ReentrantLock lock1 = new ReentrantLock();
  private static ReentrantLock lock2 = new ReentrantLock();

  private int lock;

  private IntLock(int lock) {
    this.lock = lock;
  }

  @Override
  public void run() {
    try {
      if (lock == 1) {
        lock1.lockInterruptibly();
        Thread.sleep(100);
        lock2.lockInterruptibly();
      } else {
        lock2.lockInterruptibly();
        Thread.sleep(100);
        lock1.lockInterruptibly();
      }

    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      if (lock1.isHeldByCurrentThread()) {
        lock1.unlock();
      }
      if (lock2.isHeldByCurrentThread()) {
        lock2.unlock();
      }
      System.out.println(Thread.currentThread().getName() + "：线程退出");
    }
  }

  public static void main(String[] args) throws InterruptedException {
    IntLock r1 = new IntLock(1);
    IntLock r2 = new IntLock(2);

    Thread t1 = new Thread(r1);
    t1.setName("t1");
    Thread t2 = new Thread(r2);
    t2.setName("t2");
    t1.start();
    t2.start();
    t2.interrupt();
  }
}
